<?php
use module\home\model\Profile;

define('COMMON_MESSAGE', 'COMMON_MESSAGE');

/*
 * common class of function for general usage
 * all methods will be static, therefore we do not require to create instance of
 * this class. 
 * 
 * example of usage Common::redirect($url)
 */
class Common
{
	/**
	 * storing message to the session 
	 * 
	 * if message param is given, store the message to session
	 * otherwise get the message from session, destroy the session and return message
	 * @param string $message
	 * @return string
	 */
	public static function flashMessage($message = null)
	{
		if($message) {
			$_SESSION[COMMON_MESSAGE] = $message;
		} else {
			if (isset($_SESSION[COMMON_MESSAGE])) { 
				$message = $_SESSION[COMMON_MESSAGE]; 
			}
			
			unset($_SESSION[COMMON_MESSAGE]);
			return $message;
		}
	}
	
	/**
	 * rendering the flash message to screen if available
	 *
	 * this method should be called in all flash message anticipated view scripts
	 * @return string
	 */
	public static function renderFlashMessage()
	{
		$message = self::flashMessage();

		if($message) {
			$str = "<div><b>{$message}</b></div>";
		} else {
			$str = '';
		}
		
		return $str;
	}
	
	/**
	 * redirection of location and exit from further processing
	 * 
	 * @param string 
	 */
	public static function redirect($url)
	{
		header("location:".$url);
		exit;
	}
	
	/**
	 * get the username of the logged in user
	 * @return string 
	 */
	public static function getLoginUsername()
	{
		if (Auth::hasIdentity()) {
			$user = Auth::getIdentity();
			if($user) {
				return $user->username;
			} else {
				return '';
			}
		}
	}
	
	/**
	 * returns the current login user identity
	 * 
	 * if user is not logged in, null value will be returned
	 * if user is logged in, user object  will be returned
	 * @return object|null
	 */
	public static function getLoginUser()
	{
		return Auth::getIdentity();
	}
	
	/**
	 * @return string
	 */
	public static function getLoginUserCreatedOn()
	{
		if (Auth::hasIdentity()) {
			$user = Auth::getIdentity();
			if($user) {
				return $user->created_on;
			} else {
				return '';
			}
		}
	}
	
	/**
	 * get logged in user profile
	 * @return string 
	 */
	public static function getLoginUserProfile()
	{
		if (Auth::hasIdentity()) {
			$user = Auth::getIdentity();
			if($user) {
				$account_id = $user->account_id;
				$profile = Profile::findProfileByAccountId($account_id);
				return $profile;
			} else {
				return '';
			}
		}
	}
	
	/**
	 * get logged in user profile name
	 * @return string 
	 */
	public static function getLoginProfileName()
	{
		$profile = self::getLoginUserProfile();
		return $profile->user_name;
	}
	
	/**
	 * get logged in user profile email
	 * @return string 
	 */
	public static function getLoginProfileEmail()
	{
		$profile = self::getLoginUserProfile();
		return $profile->email;
	}
	
	/**
	 * get uri, and split into array
	 * 
	 * @return array
	 */
	public static function getParam($index = null)
	{
		static $params = null;
		if(!$params) {
			$params = explode('/', $_SERVER['REQUEST_URI']);
			array_shift($params);
			array_shift($params);
			array_shift($params);
		}
		
		// if index is not given we will return
		// entire param array
		if($index === null) {
			return $params;
		}
		
		// if index provide
		// only return param by given index
		return isset($params[$index]) ? $params[$index] : null;
	}
	
	
	/**
	 * get the base url
	 * @return string 
	 */
	public static function getBaseUrl()
	{
		$protocol = isset($_SERVER['HTTPS']) ? "https" : "http";
		$url = $protocol . "://" . $_SERVER['HTTP_HOST'].'/';
		
		return $url;
	}
	
	/**
	 * dumps given variable
	 * 
	 * formats the output and also provides additional information about location and the callee
	 * 
	 * @return void|string
	 * @param mixed $var
	 * @param bool $print if set to true, then result will be printed, else returned as string
	 */
	public static function dump($var, $print = true)
	{
		
      	$trace = debug_backtrace();
	   	$lastTrace = $trace[0];
	   	$str = "<pre style='text-align:left;'><small>";
	   	$str .= "<strong>VARIABLE INFO:</strong><br />";
	   	$str .= print_r($var, true);
	   	$str .= "<br /><em>DUMP LOCATION:</em>";
	  	 $str .= "<span style='text-decoration:underline'>{$trace[0]["file"]}</span>, Line: {$trace[0]["line"]}<br />";
		
		
		if(isset($trace[1])) {
		   $str .= "CALLEE INFO:<br />";
		   $str .= "File: {$trace[1]['file']}, Line: {$trace[1]['line']}";
		}
		
	   	$str .= "</small></pre>";

		if($print) print $str;
		else return $str;
	}
	
	
	/**
	 * throws a http error to the user
	 *
	 * redirects user to the error page and exists
	 */
	public static function error($message, $code = 404)
	{
		// render error.html script
		// and exit
		include (APP_DIR . '/view/error.html');
		exit();
	}
	
	
	function removeAttributesAndGivenTags($input, $validTags = '')
	{
	    $regex = '#\s*<(/?\w+)\s+(?:on\w+\s*=\s*(["\'\s])?.+?\(\1?.+?\1?\);?\1?|style=["\'].+?["\'])\s*>#is';
	    return preg_replace($regex, '<${1}>',strip_tags($input, $validTags));
	} 
	
	function sanitizeHtml($html, $allowable_tags = null)
	{
		return $html = strip_tags($html);
/*
		$dom = new DOMDocument;                 // init new DOMDocument
		$dom->loadHTML($html);                  // load HTML into it
		$xpath = new DOMXPath($dom);            // create a new XPath
		$nodes = $xpath->query('//*[@style]');  // Find elements with a style attribute
		foreach($nodes as $node) {              // Iterate over found elements
		    $node->removeAttribute('style');    // Remove style attribute
		}
		return $dom->saveXML();                  // output cleaned HTML
*/

/*
		
		// define allowable attributes
		$allowable_atts = array('href','src','alt');
		
		// strip collector
		$strip_arr = array();
		
		// load XHTML with SimpleXML
		$data_sxml = simplexml_load_string("<root>{$html}</root>");
		
		if ($data_sxml ) {
		    // loop all elements with an attribute
		    foreach ($data_sxml->xpath('descendant::*[@*]') as $tag) {
		        // loop attributes
		        foreach ($tag->attributes() as $name=>$value) {
		            // check for allowable attributes
		            if (!in_array($name, $allowable_atts)) {
		                // set attribute value to empty string
		                $tag->attributes()->$name = '';
		                // collect attribute patterns to be stripped
		                $strip_arr[$name] = '/ '. $name .'=""/';
		            }
		        }
		    }
		    
		    // strip unallowed attributes and root tag
			$data_str = preg_replace($strip_arr,array(''),$data_sxml->asXML());
		} else {
			$data_str = strip_tags($html, $allowable_tags);
		}
		
		return $data_str;
*/
		
	}
}
?>
